package com.yuda.tools.checkanswer.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yuda.common.core.utils.StringUtils;
import com.yuda.common.core.utils.poi.ExcelUtil;
import com.yuda.common.core.web.controller.BaseController;
import com.yuda.common.core.web.domain.AjaxResult;
import com.yuda.common.core.web.page.TableDataInfo;
import com.yuda.tools.checkanswer.dto.LogContext;
import com.yuda.tools.checkanswer.dto.LogNotFound;
import com.yuda.tools.checkanswer.service.CheckLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
public class CheckLog extends BaseController {

    @Autowired
    private CheckLogService checkLogService;

    AtomicInteger canRun = new AtomicInteger(0);

    /**
     *
     * CREATE TABLE `log_student_paper` (
     *   `id` int(11) NOT NULL AUTO_INCREMENT,
     *   `student_id` varchar(32) DEFAULT NULL,
     *   `paper_id` int(11) DEFAULT NULL,
     *   `log_db_type` tinyint(1) DEFAULT '0',
     *   `log_download_type` tinyint(1) DEFAULT '0',
     *   `log_area` varchar(32) DEFAULT NULL,
     *   `log_time` varchar(32) DEFAULT NULL,
     *   PRIMARY KEY (`id`),
     *   KEY `student_id` (`student_id`)
     * ) ENGINE=InnoDB AUTO_INCREMENT=16384 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
     *
     * insert into log_student_paper (student_id,paper_id)
     *  select student_id,paper_id from sparta_exam_subject_student GROUP BY student_id,paper_id
     *
     * @param paperId
     * @return
     */
    @GetMapping("/checkLog/{paperId}")
    public String checkLog(@PathVariable("paperId") Integer paperId) {

        if (canRun.get() == 0) {
            try {
                canRun.set(1);
                checkLogService.checkLog(paperId);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                canRun.set(0);
            }
        } else {
            return "有程序正在运行";
        }
        return "完成";
    }

    @GetMapping("/listLogsNotFind")
    public TableDataInfo listLogsNotFind(LogNotFound logNotFound) {

        startPage();
        return getDataTable(checkLogService.listLogsNotFind(logNotFound));
    }

    //模糊搜索
    @GetMapping("/searchCommonExamRoom")
    public AjaxResult searchCommonExamRoom(@RequestParam("key") String key) {
        List<String> list = checkLogService.searchCommonExamRoom(key);
        return AjaxResult.success(list);
    }


    @GetMapping("/searchFromLog/{studentId}/{paperId}/{subjectId}")
    public JSONObject searchFromLog(@PathVariable("studentId") String studentId,
                                @PathVariable("paperId") Integer paperId,
                                @PathVariable("subjectId") Integer subjectId) {
        LinkedHashMap<String, List<LogContext>> integerListMap = checkLogService.searchFromLog(studentId, paperId, subjectId);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msg", "操作成功");
        jsonObject.put("code", 200);
        jsonObject.put("data", JSONObject.toJSONString(integerListMap));
        return jsonObject;
//        return AjaxResult.success(JSON.toJSON(integerListMap));
    }

    @GetMapping("/exportFromLog/{studentId}/{paperId}/{subjectId}/{pcNo}")
    public void searchFromLog(@PathVariable("studentId") String studentId,
                              @PathVariable("paperId") Integer paperId,
                              @PathVariable("subjectId") Integer subjectId,
                              @PathVariable("pcNo") String pcNo,
                              HttpServletResponse response) throws IOException {
        if(StringUtils.isEmpty(pcNo)) return;
        List<LogContext> list = checkLogService.searchFromLogWithPcNo(studentId, paperId, subjectId, pcNo.replace("号",""));
        ExcelUtil<LogContext> util = new ExcelUtil<>(LogContext.class);
        util.exportExcel(response, list, "log");
    }

}
